package cn.wp.common.core.plugin.fileserver;

import cn.hutool.core.io.FileUtil;
import cn.wp.common.core.exception.WpException;
import cn.wp.common.core.id.Id;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.InputStream;

/**
 * 存储服务
 * Created by chenyb on 2019/09/30
 */
public abstract class StorageStrategy {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected FileServerProperties fileServerProperties;

    protected void mkdir(String path){
        FileUtil.mkdir(path);
    }

    protected String genFileId(){
        return Id.genUUID();
    }

    /**
     * 文件存储
     * @param inputStream 原文件
     * @param parameter 策略参数，日期模式是可为null，主题模式时需填写具体的分类主题名
     * @param storageProcessHandler
     * @return
     */
    // 文件存储
    public FileInfo fileStore(InputStream inputStream,StrategyParameter parameter,StorageProcessHandler storageProcessHandler){
        String fileId = genFileId();
        FileInfo fileInfo = new FileInfo();
        fileInfo.setId(fileId);
        fileInfo.setOriginalName(parameter.getOriginalName());
        fileInfo.setName(fileId + "." + FileUtil.extName(parameter.getOriginalName()));
        try {
            fileInfo.setSize(inputStream.available());
        } catch (IOException e) {
            throw new WpException("获取文件大小出错",e);
        }

        // 后缀名获取
        fileInfo.setSuffix(FileUtil.extName(parameter.getOriginalName()));
        String rootPath = fileServerProperties.getRootFilePath();
        parameter.setRootPath(rootPath);
        this.store(inputStream,parameter,fileInfo,storageProcessHandler);
        logger.info("upload.file = " + JSON.toJSONString(fileInfo));
        return fileInfo;
    }

    /**
     * 存储
     * @param inputStream
     * @param parameter
     * @param fileInfo
     * @param storageProcessHandler
     */
    public abstract void store(InputStream inputStream, StrategyParameter parameter,FileInfo fileInfo,StorageProcessHandler storageProcessHandler);

}
